import * as chartsService from '../services/charts';
import testData from '../../../../mock/data.json'
console.log('33333333 ::', testData);

export default {
  namespace: 'charts',
  state: {
    list: [],
    total: null,
    page: null,
    testData: {}
  },
  reducers: {
    save(state, { payload: { data: list, total, testData } }) {
      return { ...state, list, total, testData };
    },
  },
  effects: {
    *fetch({ payload: { page } }, { call, put }) {
      const { data, headers } = yield call(chartsService.fetch, { page });
      yield put({
        type: 'save',
        payload: {
          data,
          total: parseInt(headers['x-total-count'], 10),
          page: parseInt(page, 10),
          testData: testData,
        },
      });
    },
    *remove({ payload: id }, { call, put, select }) {
      yield call(chartsService.remove, id);
      const page = yield select(state => state.users.page);
      yield put({ type: 'fetch', payload: { page } });
    },
    *patch({ payload: { id, values } }, { call, put, select }) {
      yield call(chartsService.patch, id, values);
      const page = yield select(state => state.users.page);
      yield put({ type: 'fetch', payload: { page } });
    },
    *create({payload: values}, {call, put, select}) {
      yield call(chartsService.create, values);
      const page = yield select(state => state.users.page);
      yield put({type: 'fetch', payload: {page}});
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        console.log(46, pathname, query);
        if (pathname === '/charts') {
          dispatch({ type: 'fetch', payload: query });
        }
      });
    },
  },
};
